package gui;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import tools.CheckboxUser;
import tools.OptionReader;
import calendar.CheckboxCalendar;

/**
 * 
 * @author Michi
 * 
 */
public class EditCalendar extends JFrame {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6743000717947223263L;
	private OptionReader or;
	private String[] windowColorsSeperated;
	private int r;
	private int g;
	private int b;
	private DefaultListModel dlm;
	private CheckBoxList users;
	private Connection connection;
	private Statement stat;
	private LinkedList<CheckboxUser> llUser = new LinkedList<CheckboxUser>();
	private LinkedList<Integer> selectedList = new LinkedList<Integer>();
	private int selectedID;
	private CheckboxCalendar selectedCal;
	private int addy = 0;
	private Dimension size;

	// Sprache
	int speak = 1;
	String[] fenstername = { "Kalender bearbeiten", "Edit Calendar",
			"Calendarium Editare" };
	private JTextField textField;

	/**
	 * Konstruktor
	 * 
	 * @param openedfrom
	 *            Instanz von der aus diese Klasse gestartet wurde
	 * @param selected
	 *            gewählte Checkbox
	 */
	public EditCalendar(final Object openedfrom, CheckboxCalendar selected) {
		this.selectedID = selected.getIdCalendar();
		this.selectedCal = selected;

		or = new OptionReader();
		try {
			or.getOpionsFromFile();
		} catch (IOException e2) {

			e2.printStackTrace();
		}

		String windowColors = or.getColorSetting();
		windowColorsSeperated = windowColors.split(",");
		r = Integer.parseInt(windowColorsSeperated[0]);
		g = Integer.parseInt(windowColorsSeperated[1]);
		b = Integer.parseInt(windowColorsSeperated[2]);

		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setTitle(fenstername[speak]);

		setBackground(new Color(r, g, b));
		getContentPane().setLayout(null);

		textField = new JTextField();
		textField.setBounds(20, 24, 256, 28);
		textField.setText(selected.getName());
		getContentPane().add(textField);
		textField.setColumns(10);

		dlm = new DefaultListModel();
		users = new CheckBoxList();
		users.setModel(dlm);
		// ////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////
		// /////////////////////////////////////////////////////////////////////////////

		try {
			Class.forName("com.mysql.jdbc.Driver");
			connection = DriverManager
					.getConnection("jdbc:mysql://win9142.informatik.uni-wuerzburg.de:3306?user=awesomefireballs&password=jesus");
		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();

		}
		try {
			stat = connection.createStatement();
			stat.executeQuery("use `sopra-ws12-awesome_fireballs`;");

			ResultSet alreadyInvited = stat
					.executeQuery("SELECT idUser FROM Calendar WHERE idCalendar ="
							+ selectedID + ";");

			while (alreadyInvited.next()) {
				selectedList.add(alreadyInvited.getInt("idUser"));
			}

			ResultSet idsUser = stat
					.executeQuery("SELECT idUser, name FROM User;");

			while (idsUser.next()) {

				CheckboxUser temp = new CheckboxUser(idsUser.getInt("idUser"),
						idsUser.getString("name"));

				// Fuegt alle Personen interner Liste zu um spaeter wieder auf
				// id
				// zurueckgreifen zu koennen.
				llUser.add(temp);

				JCheckBoxWithObject check = new JCheckBoxWithObject(temp);

				for (int i = 0; i < selectedList.size(); i++) {
					if (temp.getIdUser() == selectedList.get(i)) {
						check.setSelected(true);
					}
				}

				dlm.addElement(check);

			}

		} catch (SQLException e1) {
			JOptionPane.showMessageDialog(null,
					"Es konnte keine Verbindung zur Datenbank hergestellt werden",
					"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
			e1.printStackTrace();
		}

		JScrollPane bookscroller = new JScrollPane(users);
		bookscroller.setBounds(20, 54, 256, 28 * 5);
		// bookscroller.setPreferredSize(new Dimension(280, 570));

		if (selectedCal.getIdCreator() == Test.iduser) {
			getContentPane().add(bookscroller);
			addy = 28 * 5;
			size = new Dimension(300, 300);
		} else {
			size = new Dimension(300, 300 - 28 * 5);
		}

		setSize(size);
		setPreferredSize(size);
		setMinimumSize(size);
		setMaximumSize(size);

		JButton btnHinzufgen = new JButton("Hinzuf\u00FCgen");
		btnHinzufgen.setBounds(170, 63 + addy, 106, 29);
		getContentPane().add(btnHinzufgen);

		ActionListener addbtn = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				LinkedList<Integer> idadd = new LinkedList<Integer>();
				for (int i = 0; i < dlm.size(); i++) {
					JCheckBoxWithObject temp = (JCheckBoxWithObject) dlm.get(i);
					if (temp.isSelected() == true) {
						CheckboxUser temp2 = (CheckboxUser) temp.getObject();
						idadd.add(temp2.getIdUser());
					}

				}
				System.out.println(idadd.toString());
				System.out.println("Selected" + selectedList.toString());

				for (int i = 0; i < idadd.size(); i++) {
					for (int j = 0; j < selectedList.size(); j++) {
						if (idadd.get(i) == selectedList.get(j)) {
							System.out.println("removed");
							idadd.remove(i);
							selectedList.remove(j);
							i = 0;
							j = 0;
						}
					}
				}

				try {
					int idCalendar = selectedID;

					for (int i = 0; i < idadd.size(); i++) {
						if (idadd.get(i) == Test.iduser) {
							idadd.remove(i);
						}
					}

					for (int j = 0; j < selectedList.size(); j++) {
						if (selectedList.get(j) == Test.iduser) {
							selectedList.remove(j);
						}
					}

					PreparedStatement ppstdel = connection
							.prepareStatement("DELETE FROM `sopra-ws12-awesome_fireballs`.`Calendar` WHERE `idCalendar`= ? and`idUser`= ?;");
					PreparedStatement ppst = connection
							.prepareStatement("INSERT INTO Calendar VALUES( ?, ?, ?, ?, ?);");
					PreparedStatement ppstupdate = connection
							.prepareStatement("UPDATE `sopra-ws12-awesome_fireballs`.`Calendar` SET `name`=? WHERE `idCalendar`=? and`idUser`=?;");

					System.out.println(idadd.toString());

					if (selectedCal.getIdCreator() == Test.iduser) {
						connection.setAutoCommit(false);

						for (int i = 0; i < idadd.size(); i++) {
							ppst.setInt(1, idCalendar);
							ppst.setInt(2, idadd.get(i));
							ppst.setString(3, textField.getText());
							ppst.setInt(4, Test.iduser);
							ppst.setInt(5, 0);
							ppst.addBatch();
						}

						for (int j = 0; j < selectedList.size(); j++) {
							ppstdel.setInt(1, idCalendar);
							ppstdel.setInt(2, selectedList.get(j));
							ppstdel.addBatch();
							System.out.println(ppstdel.toString());
						}

						ppstdel.executeBatch();
						ppst.executeBatch();

						connection.setAutoCommit(true);
					}

					connection.setAutoCommit(false);
					ppstupdate.setString(1, textField.getText());
					ppstupdate.setInt(2, idCalendar);
					ppstupdate.setInt(3, Test.iduser);
					ppstupdate.addBatch();

					ppstupdate.executeBatch();
					connection.setAutoCommit(true);

					((Test) openedfrom).updateLeftPane(true);

					dispose();

				} catch (SQLException e) {
					JOptionPane.showMessageDialog(null,
							"Es konnte keine Verbindung zur Datenbank hergestellt werden",
							"Haaalt! Stop!", JOptionPane.ERROR_MESSAGE);
					e.printStackTrace();
				}

			}

		};

		btnHinzufgen.addActionListener(addbtn);

		JButton btnAbbrechen = new JButton("Abbrechen");
		btnAbbrechen.setBounds(61, 63 + addy, 106, 29);
		getContentPane().add(btnAbbrechen);

		ActionListener cancle = new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		};

		btnAbbrechen.addActionListener(cancle);
	}
}
